package formal.tree.recursion;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 树的高度
 * @author DengYuan2
 * @create 2021-01-10 13:29
 */
public class E_104 {
    public static void main(String[] args) {
        TreeNode t2 = new TreeNode(9);
        TreeNode t4 = new TreeNode(15);
        TreeNode t5 = new TreeNode(7);
        TreeNode t3 = new TreeNode(20, t4, t5);
        TreeNode t1 = new TreeNode(3, t2, t3);
        int r1 = maxDepth2(t1);
        System.out.println(r1);

    }

    /**
     * 我的写法-递归
     *
     * @param root
     * @return
     */
    public static int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }

    /**
     * 官方-广度优先搜索
     *
     * @param root
     * @return
     */
    public static int maxDepth2(TreeNode root) {
        if (root==null){
            return 0;
        }
        Queue<TreeNode> list = new LinkedList<>();
        list.offer(root);
        int depth = 0;
        while (!list.isEmpty()) {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = list.poll();
                if (node.left != null) {
                    list.offer(node.left);
                }
                if (node.right != null) {
                    list.offer(node.right);
                }
            }
            depth++;
        }
        return depth;
    }
}
